﻿# ------------------------------- #
# Certificate Store Configuration #
# ------------------------------- #
param([string]$virtualMachineService, [string]$virtualMachineName)

Write-Information "Virtual machine '$virtualMachineName' certificate store configuration ... " -NoNewLine $true
$userName = $subscription.virtualMachines.adminUserName
$password = $subscription.virtualMachines.password
$netBiosDomain = $subscription.virtualMachines.netBiosDomain
$uri = Get-AzureWinRMUri -ServiceName $virtualMachineService -Name $virtualMachineName
$credential = New-Object System.Management.Automation.PSCredential(($netBiosDomain + "\" + $userName), (ConvertTo-SecureString $password -AsPlainText -Force))
$session = New-PSSession -ComputerName $uri[0].DnsSafeHost -Credential $credential -Port (Get-VirtualMachineInstanceEndpointPort $subscription $virtualMachineName) -UseSSL
foreach ($certificate in $script.certificates.certificate)
{
	$certificateFile = Split-Path $certificate.file -Leaf
	Send-RemoteFile -Source "$env:dp0\Files\$($certificate.file)" -Destination "C:\$certificateFile" -Session $session
	switch ($certificate.type)
	{
		"CER"
		{
			Invoke-Command -Session $session -ScriptBlock {
				param([string]$store, [string]$file)
				certutil -addstore $store "C:\$file" | Out-Null
                Remove-Item "C:\$file" -Force
			} -ArgumentList $certificate.store, $certificateFile
		}
		"PFX"
		{
			Invoke-Command -Session $session -ScriptBlock {
				param([string]$store, [string]$file, [string]$password)
				certutil -p "$password" -importPFX $store "C:\$file" "NoExport,NoChain,NoRoot" | Out-Null
                Remove-Item "C:\$file" -Force
			} -ArgumentList $certificate.store, $certificateFile, $certificate.password
		}
		default
		{
			throw "Certificate '$($certificate.type)' is not supported."
		}
	}
}
Remove-PSSession $session
Write-Text "done."